import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';
import { useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';

// 创建 Axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:5000/api',
  timeout: 10000,
});

// 请求拦截器
// 添加请求加载动画
let loadingInstance: any;

service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 显示加载动画
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    // 在请求头中添加 token（示例）
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError) => {
    loadingInstance?.close();
    ElMessage.error('请求发送失败');
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    loadingInstance?.close();
    if (response.status === 200 && response.data) {
      return response.data;
    }
    return Promise.reject(new Error('响应数据格式错误'));
  },
  (error: AxiosError) => {
    const router = useRouter();
    if (error.response?.status === 401) {
      router.push('/login'); // 假设有登录页面
    }
    return Promise.reject(error);
  }
);

// 通用请求方法
const request = {
  get<T>(url: string, params?: object): Promise<T> {
    return service.get(url, { params });
  },
  post<T>(url: string, data?: object): Promise<T> {
    return service.post(url, data);
  },
  put<T>(url: string, data?: object): Promise<T> {
    return service.put(url, data);
  },
  delete<T>(url: string, params?: object): Promise<T> {
    return service.delete(url, { params });
  },
};

export default request;